<!DOCTYPE html>
<html lang="en" xmlns:th="https//www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<div th:replace="common/common::html"></div>
<head>
    <meta charset="UTF-8">
    <title th:text="#{role.page.title}"></title>
    <link th:href="@{/assets/css/page.css}" rel="stylesheet"/>
    <script th:inline="javascript">


        var _gridWidth;
        var _gridHeight;
        //页面自适应
        function resizePageSize(){
            _gridWidth = $(document).width()-12;/*  -189 是去掉左侧 菜单的宽度，   -12 是防止浏览器缩小页面 出现滚动条 恢复页面时  折行的问题 */
            _gridHeight = $(document).height()-65 -40; /* -32 顶部主菜单高度，   -90 查询条件高度*/
        }

        $(function () {
            resizePageSize();
            var _columnWidth = (_gridWidth-150)/3;
            $("#flexigrid-id").flexigrid({
                width : _gridWidth,
                height : _gridHeight,
                url : /*[[@{/role/queryRoleInfoListByPage}]]*/"",
                dataType : 'json',
                colModel : [
                    {display : 'roleUuid',name : 'roleUuid',width : 150,sortable : false,align : 'center',hide : 'true'},
                    {display : /*[[#{role.name}]]*/"",name : 'roleName',width : _columnWidth, sortable : true,align : 'center'},
                    {display : /*[[#{role.remarks}]]*/"",name : 'remarks',width : _columnWidth, sortable : true,align : 'center'},
                    {display : /*[[#{common.operation}]]*/"",name : 'roleUuid',width : _columnWidth, sortable : true,align : 'center',process:function (v, _tride,_row) {
                        var html = `<div>`
                            if([[${#authorization.expression("hasRole('ROLE_cldk_data_role_mod')")}]]) {
                                html += `<a href="#" class="btn" onclick="modifyRoleInfo('${v}')" title=[[#{common.modify}]]><i class="glyphicon glyphicon-pencil"></i></a>`
                            }
                            if([[${#authorization.expression("hasRole('ROLE_cldk_data_role_del')")}]]) {
                                html += `<a href="#" class="btn" onclick="deleteRoleInfo('${v}','${_row.roleName}')" title=[[#{common.delete}]]><i class="glyphicon glyphicon-trash"></i></a>`
                            }
                            if([[${#authorization.expression("hasRole('ROLE_cldk_data_role_menu')")}]]) {
                                html += `<a href="#" class="btn" onclick="allocatePermission('${v}')" title=[[#{role.allocate.permission}]]><i class="glyphicon glyphicon-share"></i></a>`
                            }
                            if([[${#authorization.expression("hasRole('ROLE_cldk_data_role_view_user')")}]]) {
                                html += `<a href="#" class="btn" onclick="viewUsersByRole('${v}', '${_row.roleName}')" title=[[#{role.view.users}]]><i class="glyphicon glyphicon-user"></i></a>`
                            }
                            html += `<div>`
                        return html;
                        }
                    },
                ],
                resizable : false, //resizable table是否可伸缩
                useRp : true,
                usepager : true, //是否分页
                autoload : false, //自动加载，即第一次发起ajax请求
                hideOnSubmit : true, //是否在回调时显示遮盖
                showcheckbox : true, //是否显示多选框
                rowhandler : rowDbclick, //是否启用行的扩展事情功能,在生成行时绑定事件，如双击，右键等
                rowbinddata : true
            });
            query()

            /**
             * 修改角色对话框
             */
            $("#modify-role-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{role.modify.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            var flag = $("form#modify-role-form-id input.form-control").checkDom()
                            if(!flag){
                                return
                            }
                            $("#modify-role-form-id").submit()
                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }//end buttons
                ]
            })//end dialog

            /**
             * 修改角色的异步表单
             */
            $("#modify-role-form-id").ajaxForm({
                dataType: "json",
                success : function(data) {
                    message(data.msg);
                    query();
                    if(data.success){
                        $("#modify-role-dialog-id").dialog('close')
                    }
                },
                error : function() {
                    message(/*[[#{common.error}]]*/'');
                },

            })//end ajaxForm

            /**
             * 增加角色对话框
             */
            $("#add-role-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{role.add.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            var flag = $("form#add-role-form-id input.form-control").checkDom()
                            if(!flag){
                                return
                            }
                            $("#add-role-form-id").submit()
                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }//end buttons
                ]
            })

            /**
             * 增加角色异步表单
             */
            $("#add-role-form-id").ajaxForm({
                dataType: "json",
                success : function(data) {
                    message(data.msg);
                    query();
                    if(data.success){
                        $("#add-role-dialog-id").dialog('close')
                    }
                },
                error : function() {
                    message(/*[[#{common.error}]]*/'');
                },

            })//end ajaxForm

            //删除角色对话框
            $("#delete-role-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{role.delete.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            var ids = $("#delete-role-dialog-id").attr("ids")

                            $.ajax({
                                type: 'post',
                                async: false,
                                dataType : 'json',
                                url: /*[[@{/role/deleteRoleByIds}]]*/'',
                                data: [{name:"ids",value:ids}],
                                success: function (data) {
                                    // console.info('deleteRoleByIds:' + JSON.stringify(data))
                                    message(data.msg)
                                    if (data.success){
                                        $("#delete-role-dialog-id").dialog('close')
                                        query()
                                    }
                                },
                                error: function(msg){
                                    message(/*[[#{common.error}]]*/'');
                                }
                            });

                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }//end buttons
                ]
            });

            //分配权限对话框
            $("#allocate-permission-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{role.allocate.permission.dialog}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            let roleUuidArray = $("#allocate-permission-dialog-id").attr('ids')
                            let menuIdArray = []
                            let treeObj =  $.fn.zTree.getZTreeObj("allocate-permission-ztree-id")
                            let nodes = treeObj.getCheckedNodes(true)
                            $(nodes).each(function (index,item) {
                                menuIdArray.push(item.id)
                            })
                            $.ajax({
                                type: 'post',
                                async: false,
                                dataType : 'json',
                                url: /*[[@{/role/saveRoleRefMenu}]]*/'',
                                data: [
                                    {name:"menuIdArray",value:menuIdArray},
                                    {name:"roleUuidArray",value:roleUuidArray},
                                ],
                                success: function (data) {
                                    // console.info(`saveRoleRefUser:${JSON.stringify(data)}`)
                                    message(data.msg)
                                    if(data.success){
                                        $("#allocate-permission-dialog-id").dialog('close')
                                    }
                                },
                                error: function(msg){
                                    message(/*[[#{common.error}]]*/'');
                                }
                            });
                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }//end buttons
                ]
            })

        })//end ready function

        function query(){

            var roleName = $("#role-name-id").val()

            $("#flexigrid-id").flexOptions({
                extParam:[
                    {name:"roleName",value:roleName},
                ]

            }).flexReload()
        }
        //双击事件
        function rowDbclick(r){
            $(r).dblclick(
                function() {
                    var columnsArray = $(r).attr('ch').split("_FG$SP_");
                    // console.info(columnsArray);
                    var roleUuid = columnsArray[0]

                    modifyRoleInfo(roleUuid);

                });
        }

        /**
         * 修改角色信息
         * @param roleUuid
         */
        function modifyRoleInfo(roleUuid) {
            $.ajax({
                    type: 'post',
                    async: false,
                    dataType : 'json',
                    url: /*[[@{/role/queryRoleInfoById}]]*/'',
                    data: [{name:"roleUuid",value:roleUuid}],
                    success: function (data) {
                        var list = $("form#modify-role-form-id input.form-control");
                        list.each(function (index,item) {
                            var name = $(item).attr("name")
                            $(this).val(data[name])
                        })

                        $("form#modify-role-form-id input.form-control").checkDom()
                        $("#modify-role-dialog-id").dialog('open')
                    },
                    error: function(msg){
                        message(/*[[#{common.error}]]*/'');
                    }
                }
            )
        }

        //增加角色
        function addRole() {
            $("form#add-role-form-id input.form-control").removeClass('ui-state-error');
            $("#add-role-form-id").resetForm();
            $("#add-role-dialog-id").dialog('open')
        }//end add role

        //删除角色
        function bathDeleteRole() {
            var ids = $("#flexigrid-id").getFlexigridiAttrByIndex(0)
            if(ids.length === 0){
                message(/*[[#{common.empty}]]*/'');
                return;
            }

            $("#delete-role-dialog-id").attr('ids',ids)

            // console.info("bathDeleteUser idx:" + JSON.stringify(ids))
            var niceNameArray = $("#flexigrid-id").getFlexigridiAttrByIndex(1)
            $("#delete-role-list-id").text(niceNameArray.join(","))
            $("#delete-role-dialog-id").dialog('open')
        }
        //单独删除角色
        function deleteRoleInfo(roleUuid,roleName) {
            $("#delete-role-dialog-id").attr('ids',roleUuid)
            $("#delete-role-list-id").text(roleName)
            $("#delete-role-dialog-id").dialog('open')
        }

        var allocateSetting = {
            check: {
                enable: true
            },
            data: {
                simpleData: {
                    enable: true
                }
            }
        };

        //批量分配权限
        function bathAllocatePermission() {
            var ids = $("#flexigrid-id").getFlexigridiAttrByIndex(0)
            if(ids.length === 0){
                message(/*[[#{common.empty}]]*/'');
                return;
            }

            allocatePermission(ids)
        }

        //分配权限
        function allocatePermission(roleUuid) {
            $("#allocate-permission-dialog-id").attr('ids',roleUuid)
            $.ajax({
                type: 'post',
                async: false,
                dataType : 'json',
                url: /*[[@{/role/queryMenuTreeListByRole}]]*/'',
                data: [{name:"roleUuid",value:roleUuid}],
                success: function (data) {
                    $.fn.zTree.init($('#allocate-permission-ztree-id'),allocateSetting,data)
                    $("#allocate-permission-dialog-id").dialog('open')

                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'');
                }
            });
        }

        // 查看拥有该角色的用户
        function viewUsersByRole(roleUuid, roleName) {
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: /*[[@{/role/queryUsersByRole}]]*/'',
                data: [{name: "roleUuid", value: roleUuid}],
                success: function (data) {
                    // 清空表格数据
                    $("#role-users-body").empty();

                    // 填充表格数据
                    if (data.length > 0) {
                        $(data).each(function(index, user) {
                            var row = `<tr>
                                <td>${user.userName}</td>
                                <td>${user.niceName}</td>
                                <td>${user.mobile || ''}</td>
                                <td>${user.email || ''}</td>
                            </tr>`;
                            $("#role-users-body").append(row);
                        });
                    } else {
                        var emptyRow = `<tr><td colspan="4" th:text="#{role.no.users}"></td></tr>`;
                        $("#role-users-body").append(emptyRow);
                    }

                    // 打开对话框
                    $("#role-users-dialog-id").dialog({
                        title: roleName + " - " + /*[[#{role.users.title}]]*/'',
                        width: 600,
                        modal: true,
                        resizable: false,
                        buttons: [
                            {
                                text: /*[[#{common.close}]]*/'',
                                click: function() {
                                    $(this).dialog("close");
                                }
                            }
                        ]
                    });
                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'');
                }
            });
        }



    </script>

</head>
<body>

    <header>
        <input id="role-name-id" th:placeholder="#{role.name.plc}">

        <a href="#" class="btn-info btn" onclick="query()">
            <i class="glyphicon glyphicon-search"></i>
            <span th:text="#{common.query}"></span>
        </a>

        <a sec:authorize="hasRole('ROLE_cldk_data_role_add')" href="#" class="btn-info btn" onclick="addRole()">
            <i class="glyphicon glyphicon-plus"></i>
            <span th:text="#{common.add}"></span>
        </a>

        <a sec:authorize="hasRole('ROLE_cldk_data_role_del')" href="#" class="btn-info btn" onclick="bathDeleteRole()">
            <i class="glyphicon glyphicon-trash"></i>
            <span th:text="#{common.delete}"></span>
        </a>

        <a sec:authorize="hasRole('ROLE_cldk_data_role_menu')" href="#" class="btn-info btn" onclick="bathAllocatePermission()">
            <i class="glyphicon glyphicon-share"></i>
            <span th:text="#{role.allocate.permission}"></span>
        </a>

    </header>
    <table id="flexigrid-id"></table>

    <div sec:authorize="hasRole('ROLE_cldk_data_role_mod')" id="modify-role-dialog-id" style="display: none">
        <form id="modify-role-form-id" method="post" th:action="@{/role/modifyRoleInfoById}">
            <div class="form-group">
                <span th:text="#{role.uuid}"></span>
                <input class="form-control" name="roleUuid" readonly>
            </div>

            <div class="form-group">
                <span th:text="#{role.name}"></span>
                <input class="form-control" name="roleName" pattern="^.{4,}$">
            </div>

            <div class="form-group">
                <span th:text="#{role.remarks}"></span>
                <input class="form-control" name="remarks" pattern="^.*$">
            </div>

        </form>
    </div>

    <div sec:authorize="hasRole('ROLE_cldk_data_role_add')" id="add-role-dialog-id" style="display: none">
        <form id="add-role-form-id" method="post" th:action="@{/role/addRoleInfoById}">

            <div class="form-group">
                <span th:text="#{role.name}"></span>
                <input class="form-control" name="roleName"
                       th:placeholder="#{role.name.plc}"
                       pattern="^.{4,}$">
            </div>

            <div class="form-group">
                <span th:text="#{role.remarks}"></span>
                <input class="form-control" name="remarks"
                       th:placeholder="#{role.remarks.plc}"
                       pattern="^.*$">
            </div>

        </form>
    </div>

    <!-- 查看角色用户的对话框 -->
    <div sec:authorize="hasRole('ROLE_cldk_data_role_view_user')" id="role-users-dialog-id" style="display: none">
        <h4 th:text="#{role.users.title}"></h4>
        <table id="role-users-table" class="table table-striped">
            <thead>
            <tr>
                <th th:text="#{user.name}"></th>
                <th th:text="#{user.nice.name}"></th>
                <th th:text="#{user.mobile}"></th>
                <th th:text="#{user.email}"></th>
            </tr>
            </thead>
            <tbody id="role-users-body">

            </tbody>
        </table>
    </div>

    <div sec:authorize="hasRole('ROLE_cldk_data_role_del')" id="delete-role-dialog-id" style="display: none">
        <span id="delete-role-list-id"></span>
    </div>

    <div sec:authorize="hasRole('ROLE_cldk_data_role_menu')" id="allocate-permission-dialog-id" style="display: none">
        <ul id="allocate-permission-ztree-id" class="ztree"></ul>
    </div>
</body>
</html>